﻿<%@ WebHandler Language="C#" Class="VeriPage" %>

using System;
using System.Web;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.SessionState;

using GDCommon.Util;

public class VeriPage : IHttpHandler, IRequiresSessionState
{
    
    public void ProcessRequest (HttpContext context) {
        //ConfigInfo config = ConfigFactory.GetConfig();
        string vcode = CreateAuthStr();
        VerifyImage verifyimg = new VerifyImage(vcode, 80, 22);
        //Context.Session["vericode"] = vcode;
      
        Bitmap image = verifyimg.Image;
        System.Web.HttpContext.Current.Response.ContentType = "image/pjpeg";
        //MemoryStream ms = new MemoryStream();
        image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

    private string CreateAuthStr(int len)
    {
        int number;
        StringBuilder checkCode = new StringBuilder();

        Random random = new Random();

        for (int i = 0; i < len; i++)
        {
            number = random.Next();

            if (number % 2 == 0)
            {
                checkCode.Append((char)('0' + (char)(number % 10)));
            }
            else
            {
                checkCode.Append((char)('A' + (char)(number % 26)));
            }

        }
        return checkCode.ToString();
    }


    private string CreateAuthStr()
    {
        int result = 0;
        string str = String.Empty;
        string[] operation = new string[] { "+", "-", "×" };
        
        Random random = new Random();
        int i = random.Next(0, 9);
        int j = random.Next(0, 9);

        int k = random.Next(0, 2);

        switch (k)
        {
            case 0:
                {
                    result = i + j;
                    break;
                }
            case 1:
                {
                    result = i - j;
                    break;
                }
            case 2: 
                {
                    result = i * j;
                    break;
                }

        }       
        

        str = i.ToString() + operation[k] + j.ToString() +"=?";

        HttpContext.Current.Session["vericode"] = result.ToString();

        return str;
    }

}